package com.changgou.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 订单页面 渲染类
 * @author 20201118
 */
@Controller
@RequestMapping("/worder")
public class OrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;

    @RequestMapping("/order")
    public String order(Model model){
        //获取用户地址信息
        List<Address> addressList = addressFeign.findByUsernameList().getData();
        model.addAttribute("addressList",addressList);

        //获取 购物车数据
        Map map = cartFeign.list().getData();
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");
        Integer totalNum = (Integer) map.get("totalNum");
        Integer totalPrice = (Integer) map.get("totalPrice");
        model.addAttribute("carts",orderItemList);
        model.addAttribute("totalNum",totalNum);
        model.addAttribute("totalPrice",totalPrice);

        //默认 地址 信息的 添加
        for (Address address : addressList) {
            if ("1".equals(address.getIsDefault())){
                //添加信息
                model.addAttribute("defaultAddr",address);
                break;
            }
        }

        return "order";
    }


    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order){
        Result result = orderFeign.add(order);
        return result;
    }

}
